package com.alibaba.user.service.impl;

import com.alibaba.basic.eum.PhoneRegisterCons;
import com.alibaba.basic.eum.ShopStateEnum;
import com.alibaba.basic.eum.WechatCons;
import com.alibaba.basic.jwt.JwtUtils;
import com.alibaba.basic.jwt.RsaUtils;
import com.alibaba.basic.jwt.UserInfo;
import com.alibaba.basic.uitl.AjaxResult;
import com.alibaba.basic.uitl.BusinessException;
import com.alibaba.basic.uitl.HttpUtil;
import com.alibaba.basic.uitl.MD5Utils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.domain.Shop;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.mapper.ShopMapper;
import com.alibaba.system.domain.Menu;
import com.alibaba.system.mapper.MenuMapper;
import com.alibaba.system.mapper.PermissionMapper;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.domain.Wxuser;
import com.alibaba.user.dto.AccountDto;
import com.alibaba.user.dto.WechatBinderDto;
import com.alibaba.user.dto.WechatDto;
import com.alibaba.user.mapper.LogininfoMapper;
import com.alibaba.user.mapper.UserMapper;
import com.alibaba.user.mapper.WxuserMapper;
import com.alibaba.user.service.LoginService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;


    // 登录
    @Override
    public AjaxResult account(AccountDto dto) {
        // 1.检验参数
        // 2.根据账号查询logininfo表数据 邮箱、手机、username都可以作为账号登录
        Logininfo logininfo = logininfoMapper.finByAccount(dto);
        if (null == logininfo){
            throw new BusinessException("账号或密码错误1");
        }
        // 3.密码是否正常
        String passParam = dto.getPassword(); // 前端传来的密码
        String passMd5 = MD5Utils.encrypByMd5(logininfo.getSalt() + passParam);
        String passwordDb = logininfo.getPassword();
        if (StringUtils.isBlank(passwordDb) || StringUtils.isBlank(passMd5) || !passMd5.equals(passwordDb)){
            throw new BusinessException("账号或密码错误");
        }
        // 4.登录成功后返还给前端数据
        // 生成token 存入到redis
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
//        Map<String, Object> map = getMap(logininfo);
        return AjaxResult.me().success(map);
    }
    /**
     * 微信扫码登陆接口
     * @param dto
     * @return
     */

    @Override
    public AjaxResult wechat(WechatDto dto) {
        // 1.校验参数
        // 2.掉微信第二接口
        String url = String.format(WechatCons.SECOND, WechatCons.APPID, WechatCons.SECRET, dto.getCode());
        // 我们后台去发送请求   jsonStr 里面获取token和openid
        String jsonStr = HttpUtil.httpGet(url);
        // 为了严谨判断一下这个
        if (StringUtils.isBlank(jsonStr)){
            throw new BusinessException("微信炸了哟乖乖");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 为了严谨我们在去判断一个非空
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openid)){
            throw new BusinessException("微信又炸了哟乖乖");
        }
        // 3.根据wxuser里面的openid去查询是否有这个人
        //  3.1 如果有让他直接登录
        Wxuser wxuser = wxuserMapper.findByopenid(openid);
        //  3,2 我们需要给前端返回这个人信息做回显
        if (wxuser != null){
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            Map<String, Object> map = this.loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().success(map);
        }
        //  3,3 如果没有，我们要强制他去绑定
        StringBuffer sbr = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=").append(openid);
        // 我们现在返回的是 success:false  msg:nobinder(没有绑定的意思)  resultObj:"?accessToken=xxxx&openId=yyy"
        return AjaxResult.me().fail("nobinder").setResultObj(sbr);
    }
    /**
     * 微信绑定接口
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechatBinder(WechatBinderDto dto) {
        // 校验参数
        // 判断电话号码和验证码是否正确
        String phoneCode = (String) redisTemplate.opsForValue().get(String.format(PhoneRegisterCons.BINDER_CODE_KEY, dto.getPhone()));
        if (StringUtils.isBlank(phoneCode)){
            throw new BusinessException("手机号码或者验证码错");
        }
        // 掉我们第三次的接口 拿到他的getAccessToken getOpenId
        String url = String.format(WechatCons.THIRD, dto.getAccessToken(), dto.getOpenId());
        // 本地访问 拿到json字符串
        String jsonStr = HttpUtil.httpGet(url);
        if (StringUtils.isBlank(jsonStr)){
            throw new BusinessException("微信叒炸了！");
        }
        // 将Json字符串变成 wxuser 对象
        Wxuser wxuser = JSONObject.parseObject(jsonStr, Wxuser.class);
            if (wxuser == null){
                throw new BusinessException("微信叕炸了！");
            }
        // user里面是否信息
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        // 如果没有 那就的添加我们user，wxuser，logininfo 三张表
        if (user == null){
            user = dto.getUser();
            // 没有
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setDisable(true);
            logininfo.setType(ShopStateEnum.WAIT_ACTIVE.getCode());
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);
        } else {
            logininfo = logininfoMapper.findByUserId(user.getId());
        }
        // 有的话就只添加一个微信user
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        // 返回登录成功
        Map<String, Object> map = this.loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().success(map);


    }

    /**
     * 微信扫码登陆接口
     * @param dto
     * @return
     */
    /*@Override
    public AjaxResult wechat(WechatDto dto) {
        // 1.校验参数
        // 2.请求微信的第二个接口 获取token和openid
        String url = String.format(WechatCons.SECOND, WechatCons.APPID, WechatCons.SECRET, dto.getCode());
        // jsonStr 里面获取token和openid
        String jsonStr  = HttpUtil.httpGet(url);
        if (StringUtils.isBlank(jsonStr)){
            throw new BusinessException("腾讯爆炸了，用不了微信了");
        }
        // 4.将字符串JSON转换为JSON对象，获取到access_token&openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken  = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openid)){
            throw new BusinessException("腾讯又爆炸了，用不了微信了");
        }
        // 3.根据openId 查询wxuser表 是否有数据
      Wxuser wxuser = wxuserMapper.findByopenid(openid);
        if (wxuser != null){
        // 4.如果有，我们就直接登录陈成功
       // - 根据wxuser中的userid查询logininfo信息
       Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            Map<String, Object> map = this.getMap(logininfo);
                return AjaxResult.me().success(map);
        }
        // 5.没有 则返回resultObj = nobinder
        StringBuffer sbr = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=").append(openid);
        // 我们现在返回的是 success:false  msg:nobinder(没有绑定的意思)  resultObj:"?accessToken=xxxx&openId=yyy"
        return AjaxResult.me().fail("nobinder").setResultObj(sbr);
    }*/


    /**
     * 微信绑定接口
     * @param
     * @return
     */
    /*@Override
    public AjaxResult wechatBinder(WechatBinderDto dto) {
        // 1.参数校验
        // 判断手机号验证码是否正确
       String phoneCode  =(String) redisTemplate.opsForValue().get(String.format(PhoneRegisterCons.BINDER_CODE_KEY,dto.getPhone()));
        if (StringUtils.isBlank(phoneCode) || !dto.getVerifyCode().equals(phoneCode)){
            throw new BusinessException("验证码错误！");
        }
        // 2.根据token和openId调用第三个接口
        String url = String.format(WechatCons.THIRD, dto.getAccessToken(), dto.getOpenId());
        String jsonStr  = HttpUtil.httpGet(url);
        if (StringUtils.isBlank(jsonStr)){
            throw new BusinessException("微信叒炸了！");
        }
        // jsonObject 会将json字符串直接转成对象 前提：字段要一样
        Wxuser wxuser = JSONObject.parseObject(jsonStr, Wxuser.class);
            if (wxuser == null){
                throw new BusinessException("微信叕炸了！");
            }
        // 根据手机号查询user里面是否有数据
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (user == null){
            // 没有 添加三张表
            user = dto.getUser();
            // 0.1.添加logininfo
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setDisable(true);
            logininfo.setType(1);
            logininfoMapper.add(logininfo);
            // 0.2.添加user
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        } else {
            logininfo = logininfoMapper.findByUserId(user.getId());
        }
        // 0.3.添加wxuser
        // 有 直接绑定wxuser
        wxuser.setUserId(user.getId());
        // 添加wxuser数据
        wxuserMapper.add(wxuser);
        // 返回登陆成功
        Map<String, Object> map = this.getMap(logininfo);
        return AjaxResult.me().success(map);

    }*/

//        // 生成uuid作为redis的key 也就是token
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
//        // 将数据返回给前端
//        // 返回数据之前 将logininfo中敏感数据 置空
//        logininfo.setPassword(null);
//        logininfo.setPhone(null);
//        logininfo.setEmail(null);
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo", logininfo);
//        return map;
//    }
        // jwt登陆方案
    /**
     * @Title: loginSuccessJwtHandler
     * @Description: 用户登录成功后生成JWT加密串并放入到map对象中
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/6/30 13:23
     * @Parameters: [cn.itsource.user.domain.Logininfo]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     */
    public HashMap<String, Object> loginSuccessJwtHandler(Logininfo logininfo){
        // 1.创建UserInfo对象，存储logininfo对象，并用于后续赋值
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);
        // 2.判断是后台用户登录才需要设置菜单信息、权限信息，类型为0那么就是后台用户登录
        if(logininfo.getType() == 0){
            // 2.1.获取用户权限信息，我们只需要sn权限编码即可
            List<String> permissions = permissionMapper.loadOwnPermissionByLogininId(logininfo.getId());
            // 2.2.获取用户菜单信息
            List<Menu> menus = menuMapper.loadOwnMenuByLogininId(logininfo.getId());
            // 2.3.将菜单信息，权限信息放入到userinfo对象中
            userInfo.setPermissions(permissions);
            userInfo.setMenus(menus);
        }
        // 3.根据密钥文件名称获取到密钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(this.getClass().getClassLoader().getResource(jwtRsaPrivate).getFile());
        // 4.根据密钥、用户信息、获取JWT加密串
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);
        // 5.按照正常逻辑我们直接返回token给前端即可，但是那样前端需要解密，我们使用简化版本JWT，还是返回用户信息
        // 封装token、用户信息、权限信息、菜单信息给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        map.put("permissions", userInfo.getPermissions());
        map.put("menus", userInfo.getMenus());
        return map;
    }
// jwt登陆方案
        private Map<String, Object> getMap(Logininfo logininfo) {
            // 将token和logininfo 返回给前端
            Map<String, Object> result = new HashMap<>();
            // 获取jwt的公钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPrivate).getFile());
            // 使用公钥 生成token
            UserInfo userInfo = new UserInfo();
            userInfo.setLogininfo(logininfo);
            // 如果是后台登陆 才有 菜单和按钮权限
            if (0 == logininfo.getType()) {
                List<Menu> menus = menuMapper.findByLogininfoId(logininfo.getId());
                userInfo.setMenus(menus);
                List<String> permissions = permissionMapper.findByLogininfoId(logininfo.getId());
                userInfo.setPermissions(permissions);
                result.put("menus", menus);
                result.put("permissions", permissions);
                // 根据logininfoid 去查询当前让你的店铺 首先你得是店铺的员工
                Employee emp = employeeMapper.findByLogininfoId(logininfo.getId());
                if (null != emp && null != emp.getShopId()) {
                    Shop shop = shopMapper.finById(emp.getShopId());
                    userInfo.setShop(shop);
//                    logininfo.setUserInfo(userInfo);
                }
            }
            // 生成token
            String token = JwtUtils.generateTokenExpireInSeconds(userInfo, privateKey, 30000000);

            // 将用户的敏感信息 清空
            logininfo.setPassword(null);
            logininfo.setPhone(null);
            result.put("token", token);
            result.put("logininfo", logininfo);
            return result;
        }
}
